package com.hy.dao;

import com.hy.bean.Manager;
import com.hy.bean.RespBean;
import com.hy.utils.DBManager;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.util.List;

/**
 *
 *
 * @Description:
 * @Author: zhangzhengwei2006
 * @Date: 2024-01-04 10:08
 *
 *
 */
public class ManagerDao {
    private QueryRunner queryRunner = new QueryRunner();

    public List<Manager> list() throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "select * from system";
        List<Manager> query = queryRunner.query(conn, sql, new BeanListHandler<>(Manager.class));
        DbUtils.close(conn);
        return query;
    }


    public Manager selectByUsername(String name) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "select * from manager where sname = ? and enable = '0'";
        Manager query = queryRunner.query(conn, sql, new BeanHandler<>(Manager.class),name);
        DbUtils.close(conn);
        return query;
    }

    public Manager selectAdmin(Integer id) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "select * from manager where sid = ? ";
        Manager query = queryRunner.query(conn, sql, new BeanHandler<>(Manager.class),id);
        DbUtils.close(conn);
        return query;
    }

    public String selectAdminPassword(Integer id) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "select spassword from manager where sid = ? ";
        String query = queryRunner.query(conn, sql, new ScalarHandler<>("spassword"), id);
        DbUtils.close(conn);
        return query;
    }

    // 修改用户信息
    public RespBean updateManager(Manager manager) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "update manager set sName = ?,sGender = ?,mailbox = ?,telephone = ? where sid = ?";
        int query = queryRunner.update(conn, sql, manager.getSname(),manager.getSgender(),manager.getMailbox(),manager.getTelephone(),manager.getSid());
        if (query > 0)
            return RespBean.success("修改成功");
        DbUtils.close(conn);
        return RespBean.success("修改失败");
    }

    public RespBean updatePassword(Integer id, String password) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "update manager set sPassword = ? where sId = ?";
        int query = queryRunner.update(conn, sql, password,id);
        if (query > 0)
            return RespBean.success("修改成功");
        DbUtils.close(conn);
        return RespBean.success("修改失败");
    }
}
